package com.tbdp.lsmp.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 资源加载工具类
 *
 * @author xingbingbing.xb
 * @version $Id: ResourceUtil.java, v 0.1 2015-10-13 下午7:30:25  xingbingbing.xb Exp $
 */
public class ResourceUtil {

    /**
     * 获取文件输入流
     */
    public static InputStream getInputStream(String modelFile) throws IOException {
        InputStream ins = getResourceAsStream(modelFile);
        if (ins == null) {
            File f = new File(modelFile);
            if (f.exists()) {
                ins = new FileInputStream(f);
            }
        }
        return ins;

    }

    /**
     * 获取文件输入流
     */
    public static InputStream getResourceAsStream(String resource) throws IOException {
        URL url = null;
        try {
            url = getResource(resource);
            if (url != null) {
                return url.openStream();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * @return url
     */
    public static URL getResource(String resource) {

        URL url;
        //Try with the Thread Context Loader.
        ClassLoader classLoader = null;

        //Let's now try with the classloader that loaded this class.
        classLoader = ResourceUtil.class.getClassLoader();
        if (classLoader != null) {
            url = classLoader.getResource(resource);
            if (url != null) {
                return url;
            }
        }

        classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader != null) {
            url = classLoader.getResource(resource);
            if (url != null) {
                return url;
            }
        }

        //Last ditch attempt. Get the resource from the classpath.
        return ClassLoader.getSystemResource(resource);
    }

}
